<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
	
    <el-dialog :title="title" :visible.sync="dialogVisible" width="80%" v-dialogDrag append-to-body >
		
		<el-tabs v-model="activeName" type="card" @tab-click="handleClick">
		   <el-tab-pane label="基本信息" name="first">
			   <el-form  ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
			   			<el-form-item label="类型系列" prop="type">
			   				<el-select v-model="formData.type" placeholder="请选择类型系列">
			   					  <el-option v-for="dict in this.getDictDatas('team_linetype')" :key="dict.value"
			   						:label="dict.label" :value="dict.value" />
			   				</el-select>
			   				<el-checkbox style="margin-left: 20px;" v-model="formData.breakst">散客线路请打勾</el-checkbox>
			   			</el-form-item>
			             <el-form-item label="线路名称" prop="name">
			               <el-input v-model="formData.name" placeholder="请输入线路名称" />
			             </el-form-item>
			             <el-form-item label="线路" prop="nameLin">
			               <el-input v-model="formData.nameLin" placeholder="请输入线路" />
			             </el-form-item>
			             
			             <el-form-item label="代号" prop="number">
			               <el-input v-model="formData.number" placeholder="请输入代号" />
			             </el-form-item>
			             <el-form-item label="天数" prop="days">
			   					<el-input-number v-model="formData.days"  :min="1" :max="20" label="天数"></el-input-number>
			             </el-form-item>
			             <el-form-item label="排序" prop="sort">
			               <el-input v-model="formData.sort" placeholder="请输入排序" />
			             </el-form-item>
			             <el-form-item label="住宿说明" prop="remarkStay">
			               <el-input v-model="formData.remarkStay" placeholder="请输入住宿说明" />
			             </el-form-item>
			             <el-form-item label="注意事项" prop="attention">
			               <el-input v-model="formData.attention" placeholder="请输入注意事项" />
			             </el-form-item>
			             <el-form-item label="是否有效" prop="isEffective">
			   				  <el-checkbox v-model="formData.isEffective">是否有效</el-checkbox>
			   				  <el-checkbox v-model="formData.isSingle">是否单订</el-checkbox>
			             </el-form-item>
			             <el-form-item label="使用说明" prop="remak">
			               <el-input v-model="formData.remak" placeholder="请输入使用说明" />
			             </el-form-item>
			                
			   </el-form>
			         
		   </el-tab-pane>
		   <el-tab-pane label="线路行程" name="second" v-if="formData.id!=null">
			   <el-row>
			       <el-col :span="15">
					   <table class="table-bordered" >
					   	<tbody>
					   		<tr>
					   			<th>日期</th>
					   			<th>住宿</th>
					   			<th>早</th>
					   			<th>中</th>
					   			<th>晚</th>
					   			<th>景点</th>
					   		</tr>
							<!-- <tr v-for="(item,index) in linData" @click="selectRow(index)" :class="{ 'selected-row': index === selectedRowIndex }" :key="index" :data-row-index="index" draggable="true"  @dragover.prevent @drop="handleDrop($event,index)"> -->
					   		<tr v-for="(item,index) in linData" @click="selectRow(index)" :class="{ 'selected-row': index === selectedRowIndex }" :key="index" >
					   			<td style="width: 100px;"><el-input v-model="item.dates" placeholder="请输入" /></td></td>
					   			<td> <el-input v-model="item.stay" placeholder="请输入" /></td>
					   						<td style="width: 130px;">
					   							
					   							<el-select v-model="item.morning" placeholder="请输入">
					   							      <el-option v-for="dict in zhaocanData" :key="dict.label"
					   							        :label="dict.label" :value="dict.label" />
					   							</el-select>
					   						</td>
					   						<td style="width: 130px;">
					   							<el-select v-model="item.noon" placeholder="请输入">
					   							      <el-option v-for="dict in zhongcanData" :key="dict.label"
					   							        :label="dict.label" :value="dict.label" />
					   							</el-select>
					   						</td>
					   						<td style="width: 130px;">
					   							<el-select v-model="item.evening" placeholder="请输入">
					   							      <el-option v-for="dict in wancanData" :key="dict.label"
					   							        :label="dict.label" :value="dict.label" />
					   							</el-select>
					   						</td>
					   						<td style="width: 30%;">
												<div class="view">
													<tr v-for="(item2, index2) in item.view" :key="index2" @mousedown="startDrag($event, index2)">
													  <td :style="{ width: itemWidth + 'px' }" draggable="true" @dragstart="dragStart($event)" @dragover.prevent @drop="drop($event, index2,index)">
													    {{ item2.name }}<el-link type="danger" style="float: right;" @click="viewClickDel(index2,index)">删除</el-link>
													  </td> 
													</tr>
												</div>
												<!-- <el-button type="warning" size="mini" v-for="(item,index) in item.view" >{{item.name}}</el-button> -->
												
											</td>
											<td style="width: 100px;padding-left: 20px;" >
												 <el-button size="mini" type="text" @click.prevent="removeDomain(item,2)">删除</el-button>
											</td>
										
					   					</tr>	
					   		</tbody>		
					   </table>
				   </el-col>
			   	  
			   	</el-col>
			    <el-col :span="9">
			        <el-tabs v-model="activeName2" type="card"   @tab-click="tabsScenicspotType">
			            <el-tab-pane label="常用景点" name="first">
							<div >
								<el-button type="warning" size="mini" v-for="(item,index) in scenicspotType" @click="scenicspotClick(item)">{{item.name}}</el-button>
							</div>
						</el-tab-pane>
			            <el-tab-pane label="虚拟景点" name="second">
							<div >
								<el-button type="warning" size="mini" v-for="(item,index) in scenicspotType" @click="scenicspotClick(item)">{{item.name}}</el-button>
							</div>
						</el-tab-pane>
			            <el-tab-pane label="搜索" name="third">
							<div >
							    <el-input placeholder="请输入内容" v-model="scenicspotName" class="input-with-select" style="width: 300px;">
							    <el-button slot="append" icon="el-icon-search" @click="scenicspotNameClick()"></el-button>
							  </el-input>
							</div>
							<div style="margin-top: 10px;">
								<el-button type="warning" size="mini" v-for="(item,index) in scenicspotType" @click="scenicspotClick(item)">{{item.name}}</el-button>
							</div>
						</el-tab-pane>
			        </el-tabs> 
			    </el-col>
			   </el-row>
			   
		   </el-tab-pane>
		 </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false" >取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
	import * as LineTripApi from '@/api/team/linetrip';
	import Sortable from 'sortablejs';// 引入 SortableJS 的样式，如果你需要的话
  import * as LineApi from '@/api/team/line';
  import * as ScenicspotApi from '@/api/team/scenicspot';
  import { getDictDatas, DICT_TYPE } from '@/utils/dict'
      export default {
    name: "LineForm",
    components: {
                    },
    data() {
      return {
		 activeName: 'first',
		 activeName2: 'first',
		 scenicspotList:[],//景点资料
		 scenicspotType:[],
		 scenicspotName:undefined,
		 selectedRowIndex:0,
		 itemWidth: 50, // 单元格宽度，可以根据需要调整
		 dragSrcIndex: null, // 拖拽源元素的索引
		 dragging: false, // 是否正在拖拽的标志
		 hoveredRowIndex:null,//鼠标悬停的下标
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        dialogVisible: false,
        // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
        formLoading: false,
		zhaocanData: this.getDictDatas(DICT_TYPE.team_zhaocan),
		zhongcanData: this.getDictDatas(DICT_TYPE.team_zhongcan),
		wancanData: this.getDictDatas(DICT_TYPE.team_wancan),
		linData:[
			{
				dates:"",
				stay:"",
				morning:"",
				noon:"",
				evening:"",
				view:"",
			}
		],
        // 表单参数
        formData: {
                            id: undefined,
                            name: undefined,
                            nameLin: undefined,
                            type: undefined,
                            number: undefined,
                            days: undefined,
                            sort: undefined,
                            remarkStay: undefined,
                            attention: undefined,
                            isEffective: undefined,
                            remak: undefined,
                            breakst: undefined,
                            isSingle: undefined,
                            column1: undefined,
                            column2: undefined,
                            column3: undefined,
                            column4: undefined,
                            column5: undefined,
        },
        // 表单校验
        formRules: {
                        name: [{ required: true, message: '线路名称不能为空', trigger: 'blur' }],
                        nameLin: [{ required: true, message: '线路不能为空', trigger: 'blur' }],
                        type: [{ required: true, message: '类型系列不能为空', trigger: 'change' }],
                        days: [{ required: true, message: '天数不能为空', trigger: 'blur' }],
                        breakst: [{ required: true, message: '散/团不能为空', trigger: 'blur' }],
        },
         };
    },
	created() {
	  this.getList();
	},
    methods: {
		
		/** 查询景点资料列表 */
		async getList() {
		  try {
		    const res = await ScenicspotApi.getScenicspotList();
			console.log("查询景点资料列表",res.data)
			this.scenicspotList= res.data.reverse();;
			this.scenicspotType=this.scenicspotList.filter(item => item.ischangyong === "是");
			console.log("this.scenicspotList",this.scenicspotList)
		  } finally {
		   
		  }
		},
		//选中的景点
		scenicspotClick(item){
			//console.log("选中的景点",item)
			let data=this.linData[this.selectedRowIndex].view.filter(row => row.id == item.id);
			//console.log("选中的景点data",data)
			if(data.length>0){return;}
			//判断是否存在景点
			this.linData[this.selectedRowIndex].view.push({
				name:item.name,
				id:item.id
			})
		},
		//删除线路行程
		removeDomain(item,idnbem){
			var index = this.linData.indexOf(item)
			//判断是否存在团款id
			if(this.linData[index].id){
				console.log("this.linData[index].id",this.linData[index])
				this.handleDeleteBatch(this.linData[index].id,index)
				return
			}
			if (index !== -1) {
			  this.linData.splice(index, 1)
			}
		},
		/** 批量删除线路模板—行程 */
		async handleDeleteBatch(id,index) {
		  await this.$modal.confirm('是否确认删除?'+id)
		  try {
		    await LineTripApi.deleteLineTrip(id);
		    this.$modal.msgSuccess("删除成功");
			this.linData.splice(index, 1)
		  } catch {}
		},
		selectRow(index) {
		    this.selectedRowIndex = index;
		  },
      /** 打开弹窗 */
     async open(id) {
        this.dialogVisible = true;
        this.reset();
		
        // 修改时，设置数据
        if (id) {
          this.formLoading = true;
          try {
            const res = await LineApi.getLine(id);
            this.formData = res.data;
			this.showLineTrip(this.formData.id);
            
          } finally {
			this.title = "修改"+"【"+this.formData.name+"】";
            this.formLoading = false;
          }
		  return
        }
        this.title = "新增线路";
    },
      /** 提交按钮 */
      async submitForm() {
			// 校验主表
			await this.$refs["formRef"].validate();
					  this.formLoading = true;
			try {
			  const data = this.formData;
					  // 修改的提交
			  if (data.id) {
			   await LineApi.updateLine(data);
				this.$modal.msgSuccess("修改成功");
				this.dialogVisible = false;
				this.$emit('success');
				//添加行程信息
				let row =JSON.parse(JSON.stringify(this.linData))
				row.map(person => person.view=JSON.stringify(person.view));
				console.log("添加行程信息",row)
				await LineTripApi.createUpdateBatchLineTrip(row);
				
				return;
			  }
			  // 添加的提交
			  await LineApi.createLine(data);
			  this.$modal.msgSuccess("新增成功");
			  this.dialogVisible = false;
			  this.$emit('success');
			} finally {
			  this.formLoading = false;
			}
      },
	  //查询景点名称
	 async scenicspotNameClick(){
		 
		 try {
			  const res = await ScenicspotApi.getScenicspotPage({
				  pageNo: 1,
				  pageSize: 99,
				  name: this.scenicspotName,
			  });
			  this.scenicspotType=res.data.list;
		  }finally {
       
		}
	  },
	  //景点虚拟景点切换
	  tabsScenicspotType(tab, event){
		  
		  console.log("景点虚拟景点切换",tab.index);
		  if(tab.index==0){
			   console.log("1");
			  this.scenicspotType=this.scenicspotList.filter(item => item.ischangyong === "是");
		  }
		  if(tab.index==1){
			   console.log("2");
		  	  this.scenicspotType=this.scenicspotList.filter(item => item.isactual === "虚拟景点");
		  }
		  if(tab.index==2){
			   this.scenicspotType=[]
		  }
	  },
	  //查询线路行程
	  async showLineTrip(id){
		  try {
		    const res = await LineTripApi.getLineTripPage({
				pageNo: 1,
				pageSize: 20,
				type: 1,
				column1:id,
			});
			if(res.data.list.length>0){
				
				this.linData =res.data.list.reverse();
				this.linData.map(person => person.view=JSON.parse(person.view)); 
				let nubm=this.formData.days-this.linData.length;
				if(nubm>0){
					for (let i = 1; i <= nubm; i++) {
					    this.linData.push(
							{ dates:`${this.linData.length + 1}`,type: 1,stay:"",morning:"",noon:"",evening:"",view:[],column1:this.formData.id }
						);
						
					}
					
				}
				//console.log("查询线路行程",res.data)
			}else{
				//console.log("查询线路行程2")
				this.linData=Array.from({ length: this.formData.days }, (_, i) => ({ dates:`${i + 1}`,type: 1,stay:"",morning:"",noon:"",evening:"",view:[],column1:this.formData.id }));
            }
		  } finally {
		   
		  }
	  },
	  handleClick(tab, event) {
	    console.log(tab.VueComponent);
		
		if(tab.index==1){
			let nubm=this.formData.days-this.linData.length;
			if(nubm>0){
				for (let i = 1; i <= nubm; i++) {
				    this.linData.push(
						{ dates:`${this.linData.length + 1}`,type: 1,stay:"",morning:"",noon:"",evening:"",view:[],column1:this.formData.id }
					);
					
				}
				
			}
			 return
		 }
		
	    },
		//控制景点拖动
		handleDrop(event,index) {
		
		  // console.log(`按钮拖动到行${index}`);
		
		},
		startDrag(event, index) {
		  this.dragSrcIndex = index;
		  this.dragging = true;
		},
		dragStart(event) {
		  event.dataTransfer.setData("text", event.target.innerText);
		  event.dataTransfer.effectAllowed = 'move';
		},
		drop(event, dropIndex,itemIndex) {
			//console.log("dragSrcIndex",this.dragSrcIndex)
		  if (this.dragSrcIndex !== dropIndex) {
		    const movedItem = this.linData[itemIndex].view.splice(this.dragSrcIndex, 1)[0];
			//console.log("movedItem",movedItem)
		    this.linData[itemIndex].view.splice(dropIndex, 0, movedItem);
		    this.dragSrcIndex = null; // 重置拖拽源索引
		  }
		  this.dragging = false; // 停止拖拽状态
		},
		//删除景点
		viewClickDel(dropIndex,itemIndex){
			 this.linData[itemIndex].view.splice(dropIndex, 1);
		},
                      /** 表单重置 */
      reset() {
		  this.activeName2='first';
		  this.activeName='first',
        this.formData = {
                            id: undefined,
                            name: undefined,
                            nameLin: undefined,
                            type: undefined,
                            number: undefined,
                            days: undefined,
                            sort: undefined,
                            remarkStay: undefined,
                            attention: undefined,
                            isEffective: undefined,
                            remak: undefined,
                            breakst: undefined,
                            isSingle: undefined,
                            column1: undefined,
                            column2: undefined,
                            column3: undefined,
                            column4: undefined,
                            column5: undefined,
        };
        this.resetForm("formRef");
      }
    }
  };
</script><style scoped>
	.view{
		td {
		  width: 250px !important;
		  border: 1px solid #ccc;
		  text-align: left;
		  cursor: move; /* 显示可拖动的光标 */
		  user-select: none; /* 防止文本被选中 */
		}
	}
	.selected-row {
	  background-color: #e3ebf1; /* 或者你喜欢的任何颜色 */
	}
	.borders{
		border: solid 1px #dadada;
		    padding-top: 10px;
		.el-form-item { 
			margin-bottom:12px !important;
		}
		
	}
	
	table {
	    border-spacing: 0;
	    border-collapse: collapse;
	}
	.table-bordered {
	    border: 1px solid #95bce2;
	}
	.table-bordered>tbody>tr>td, 
	.table-bordered>tbody>tr>th,
	.table-bordered>tfoot>tr>td,
	.table-bordered>tfoot>tr>th,
	.table-bordered>thead>tr>td, 
	.table-bordered>thead>tr>th{
		border: 1px solid #ddd;
		padding: 5px 10px;
		
	}
	.table-bordered > thead > tr > th, 
	.table-bordered > tbody > tr > th, 
	.table-bordered > tfoot > tr > th, 
	.table-bordered > thead > tr > td, 
	.table-bordered > tbody > tr > td, 
	.table-bordered > tfoot > tr > td{
	    border: 1px solid #95bce2;
	}
	table th {
	   background-color: #c5ddf1;
	   
	   
	}
	table td{
		padding-top: 5px;
	}
	
</style>